package com.flying.carclub.utils;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.StrikethroughSpan;

import com.flying.carclub.http.NameValuePair;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhuxiaocheng on 2018/1/23.
 */

public class StringUtil {

    /**
     * 将string转为int ，异常时返回-1
     *
     * @param s
     * @return
     */
    public static int parseInt(String s) {
        int i = 0;
        try {
            i = Integer.parseInt(s);
        } catch (Exception e) {
            e.printStackTrace();
            i = -1;
        }
        return i;
    }

    /**
     * 将string 转为long,异常时返回-1
     *
     * @param s
     * @return
     */
    public static long parseLong(String s) {
        long i = 0L;
        try {
            i = Long.parseLong(s);
        } catch (Exception e) {
            e.printStackTrace();
            i = -1L;
        }
        return i;
    }

    /**
     * 将string 转为float,异常时返回-1
     *
     * @param s
     * @return
     */
    public static float parseFloat(String s) {
        float i = 0f;
        try {
            i = Float.parseFloat(s);
        } catch (Exception e) {
            e.printStackTrace();
            i = -1f;
        }
        return i;
    }

    /**
     * 将string 转为double,异常时返回-1
     *
     * @param s
     * @return
     */
    public static double parseDouble(String s) {
        double i = 0;
        try {
            i = Double.parseDouble(s);
        } catch (Exception e) {
            e.printStackTrace();
            i = -1;
        }
        return i;
    }

    /**
     * 取字串小数点前整数
     *
     * @param s
     * @return
     */
    public static String toIntString(String s) {
        String intString = "";
        try {
            if (s.contains("."))
                intString = s.substring(0, s.indexOf("."));
            else
                intString = s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return intString;
    }

    /**
     * 判断字串是否是数字
     *
     * @param str
     * @return
     */
    public static int isNumString(String str) {
        Pattern p = Pattern.compile("[0-9]*");// 格式"a"
        Matcher m = p.matcher(str);
        if (m.matches()) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 输入 的字串不包含特殊字符
     *
     * @param string
     * @return 不包则返回true 否则 返回 false
     */
    public static boolean isConSpeCharacters(String string) {
        if (string.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 计算EditText中输入字串的长度(按字节计算)
     *
     * @param temp
     * @return
     */
    public static int strlen(CharSequence temp) {
        if (temp == null || temp.length() <= 0) {
            return 0;
        }

        int len = 0;
        char c;
        for (int i = temp.length() - 1; i >= 0; i--) {
            c = temp.charAt(i);
            if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                // 字母, 数字
                len++;
            } else {
                if (Character.isLetter(c)) { // 中文
                    len += 2;
                } else { // 符号或控制字符
                    len++;
                }
            }
        }

        return len;
    }

    /**
     * 将年，月，日，时，分，拼成14位长度的字串
     *
     * @param _year
     *            年
     * @param _month
     *            月
     * @param _day
     *            日
     * @param _hour
     *            时
     * @param _minute
     *            分
     * @return 14位长度的字串
     */
    public static String formatDateString(int _year, int _month, int _day, int _hour, int _minute) {
        String value = String.valueOf(_year);
        if (_month < 10)
            value += "0" + _month;
        else
            value += _month;

        if (_day < 10)
            value += "0" + _day;
        else
            value += _day;

        if (_hour < 10)
            value += "0" + _hour;
        else
            value += _hour;

        if (_minute < 10)
            value += "0" + _minute;
        else
            value += _minute;

        value += "00";
        return value;
    }

    /**
     * 将年，月，日拼成一个8位长的字串
     *
     * @param year
     *            年
     * @param month
     *            月
     * @param day
     *            日
     * @return 8位长的字串
     */
    public static String formatDateString(int year, int month, int day) {
        String value = String.valueOf(year);
        while (value.length() < 4) {
            value = "0" + value;
        }
        if (month < 10)
            value += "0" + month;
        else
            value += month;

        if (day < 10)
            value += "0" + day;
        else
            value += day;

        return value;
    }



    /**
     * 将str中含有src的替换成aim str与src 不能为空。
     *
     * @param str
     * @param src
     * @param aim
     * @return
     */
    public static String replaceStr(String str, String src, String aim) {
        if (TextUtils.isEmpty(str) || TextUtils.isEmpty(src)) {
            return "";
        }
        if (str.contains(src)) {
            return str.replace(src, aim);
        }
        return str;
    }

    /**
     * string是否有效
     *
     * @param inputStr
     * @return
     */
    public static boolean isValidStr(String inputStr) {
        char[] charArray = inputStr.toCharArray();
        int length = charArray.length;
        for (int i = 0; i < length; i++) {
            if (!(charArray[i] >= '0' && charArray[i] <= '9') && !(charArray[i] >= 'A' && charArray[i] <= 'z') && charArray[i] != '_')
                return false;
        }

        return true;
    }

    /**
     * 返回一个中间有线的SpannableString
     *
     * @param s
     * @return
     */
    public static SpannableString getMidLineStr(String s) {
        SpannableString ss = new SpannableString(s);
        ss.setSpan(new StrikethroughSpan(), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

    /**
     * 将日期拆分并将年月日存入数组中
     *
     * @param date
     * @return
     */
    public static int[] getDateField(String date) {
        if (date != null && date.length() >= 8) {
            int[] fields = new int[3];
            fields[0] = parseInt(date.substring(0, 4));
            String month = date.substring(4, 6);
            fields[1] = parseInt(month) - 1;
            String day = date.substring(6, 8);
            fields[2] = parseInt(day);
            return fields;
        }
        return null;
    }

    /**
     * 将年，月，日 ，三个值拼成 YYYY-MM-DD
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static String dateToString(int year, int month, int day) {
        if (year < 0 || month < 0 || day < 0)
            return "";
        else
            return year + "-" + month + "-" + day;
    }

    /**
     * 校验yyyyMMdd日期是否合法
     *
     * @param date
     * @return 八位的年月日
     */
    public static boolean isDateRight(String date) {
        if (date.length() == 8) {
            int year = -1;
            int month = -1;
            int day = -1;
            boolean isLeapYear = false;// 闰年
            year = parseInt(date.substring(0, 4));
            month = parseInt(date.substring(4, 6));
            day = parseInt(date.substring(6, 8));
            if (year / 4 == 0 && year / 100 != 0) {
                isLeapYear = true;// 闰年
            }
            if (year / 400 == 0) {
                isLeapYear = true;// 闰年
            }
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    if (day <= 31 && day >= 1) {
                        return true;
                    }
                    break;
                case 2:
                    if (isLeapYear) {
                        if (day <= 29 && day >= 1) {
                            return true;
                        }
                    } else {
                        if (day <= 28 && day >= 1) {
                            return true;
                        }
                    }
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    if (day <= 30 && day >= 1) {
                        return true;
                    }
                    break;
                default:
                    return false;
            }
            return false;
        }
        return false;
    }

    /**
     * 验证输入的手机号:长度为11位，且为纯数字，首位为1
     *
     * @param mobile
     * @return
     */
    public static boolean isMobileNumber(String mobile) {
        if (mobile.length() == 11 && StringUtil.isNumString(mobile) == 1 && mobile.startsWith("1")) {
            return true;
        }
        return false;
    }

    /**
     * email是否合法，只校验是否是xx@xx.xx的三段形式
     *
     * @param email
     * @return true or false
     */
    public static boolean isValidEMail(String email) {
        Pattern p = Pattern.compile("\\S+@(\\S+\\.)+[\\S]{1,6}");
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 读取文本文件中的字符串
     *
     * @param file
     * @return
     */
    public static String readStringFromFile(File file) {
        InputStream is = null;
        String ret = "";
        try {
            if (!file.exists())
                return "";
            is = new BufferedInputStream(new FileInputStream(file));
            long contentLength = file.length();
            ByteArrayOutputStream outstream = new ByteArrayOutputStream(contentLength > 0 ? (int) contentLength : 1024);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) > 0) {
                outstream.write(buffer, 0, len);
            }
            outstream.close();
            ret = outstream.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
        return ret;
    }

    /**
     * 格式化字符串 在数字间加入逗号。如 1,000
     *
     * @param num
     *            String
     * @return
     */
    public static String formateNumString(String num) {

        if (num == null || "".equals(num))
            return "";
        if (num.length() < 4)
            return num;
        int i = num.length();
        String result = num.substring(i - 3, i);
        i = i - 3;
        while (i - 3 > 0) {
            result = num.substring(i - 3, i) + "," + result;
            i = i - 3;
        }
        result = num.substring(0, i) + "," + result;
        return result;
    }

    /**
     * 格式化字符串 在数字间加入逗号。如 1,000
     *
     * @param num
     *            int
     * @return
     */
    public static String formateNumString(int num) {
        String numString = String.valueOf(num);
        return formateNumString(numString);
    }



    public static String getFormatedServiceNumber(String number) {
        if (!TextUtils.isEmpty(number)) {
            if (number.length() == 10) {
                return number.substring(0, 3) + "-" + number.substring(3, 6) + "-" + number.substring(6, 10);
            }
        }
        return number;
    }

    /**
     * 将可变参数NameValuePair转换为list
     *
     * @param nameValuePairs
     * @return
     */
    public static ArrayList<NameValuePair> stripNulls(NameValuePair... nameValuePairs) {
        ArrayList<NameValuePair> params = new ArrayList<>();
        for (NameValuePair param : nameValuePairs) {
            if (param.getValue() != null) {
                params.add(param);
            }
        }
        return params;
    }
}

